<?php

namespace App\Http\Resources;

use App\Models\CommentModel;
use App\Models\UserModel;
use Carbon\Carbon;
use Illuminate\Http\Resources\Json\JsonResource;

class DocumentModelResource extends JsonResource
{
    public function toArray($request): array
    {
        return [
            'id'            => $this->id,
            'uid'           => $this->uid,
            'doc_type'      => $this->doc_type,
            'type'          => $this->type,
            'title'         => $this->title,
            'covers'        => $this->getImageList($this->covers),
            'crops'         => $this->getImageList($this->crops),
            'file'          => $this->getFilePath($this->file),
            'poster'        => $this->getFilePath($this->poster),
            'content'       => $this->content,
            'user'          => UserModel::where('id', $this->uid)->first(),
            'views'         => $this->views,
            'comment_count' => $this->comment_count,
            'praise_count'  => $this->praise_count,
            'comments'      => CommentModelResource::collection(CommentModel::where('did', $this->id)->get()),
            'praise_flag'   => 0,
            'created_at'    => Carbon::parse($this->created_at)->toDateTimeString(),
        ];
    }

    /**
     * 获取图片数组
     * @param $images
     * @return array
     */
    private function getImageList($images): array
    {
        $imageList = json_decode($images, true);
        $data = [];
        if ($imageList) {
            foreach ($imageList as $imageFile) {
                $data[] = [
                    'cover'         => url( 'storage/' . $imageFile),
                    'watermarked'   => '',
                    'desc'          => '',
                ];
            }
        }
        return $data;
    }

    /**
     * 获取文件路径
     * @param $file
     * @return array|object
     */
    private function getFilePath($file) {
        return $file ? ['path' => url( 'storage/' . $file)] : (object)[];
    }
}
